package com.lianzai.wxapp.controller;

import com.alibaba.fastjson.JSONObject;
import com.lianzai.car.domain.CarInfoDO;
import com.lianzai.car.service.CarInfoService;
import com.lianzai.common.annotation.NoLoginAuthRequired;
import com.lianzai.common.config.RedisUtils;
import com.lianzai.common.config.SendMailConfig;
import com.lianzai.common.config.WxConfig;
import com.lianzai.common.utils.*;
import com.lianzai.mobile.domain.CarPriceRelaDO;
import com.lianzai.mobile.domain.CommunityInfoDO;
import com.lianzai.mobile.service.CarPriceRelaService;
import com.lianzai.mobile.service.CommunityInfoService;
import com.lianzai.shop.service.ShopService;
import com.lianzai.user.domain.UserInfoDO;
import com.lianzai.user.service.UserInfoService;
import com.lianzai.util.FileUtil;
import com.lianzai.wxapp.domain.MerchantRegisterInfo;
import com.lianzai.wxapp.domain.ResidentRegisterInfo;
import com.lianzai.wxapp.service.MerchantService;
import com.lianzai.wxapp.service.ResidentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.util.List;

@Slf4j
@Controller
public class RegisterController {

    @Value("${license.windows-path}")
    private String licenseWinPath;

    @Value("${license.linux-path}")
    private String licenseLinuxPath;

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    ShopService shopService;


    @Value("${server.domain-index}")
    private String index;

    @Autowired
    private SendMailConfig sendMailConfig;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private ResidentService residentService;

    @Autowired
    private CarInfoService carInfoService;

    @Autowired
    private CommunityInfoService communityInfoService;

    @Autowired
    private CarPriceRelaService carPriceRelaService;

    /**
     * 发送短信验证码
     * @return
     */
//    @NoLoginAuthRequired
//    @RequestMapping(value ="/wxapp/sendRegMsgCode", method = RequestMethod.POST)
//    @ResponseBody
//    public R sendRegMsgCode(@RequestParam("mobile") String mobile,
//                            @RequestParam("code") String code,
//                            HttpServletRequest httpServletRequest){
//        if(StringUtils.isEmpty(mobile) || mobile.length()!=11){
//            return R.error("手机号码输入不合法");
//        }
//
//        String kaptchaCode = (String) httpServletRequest.getSession().getAttribute("rightCode");
//        if(StringUtils.isEmpty(kaptchaCode)){
//            return R.error("验证码未找到");
//        }
//
//        if(!code.equals(kaptchaCode)){
//            return R.error("验证码输入错误");
//        }
//        String msgCode = UUIDUtil.generateInteger(4);
//        sendMailConfig.sendRegMsg(msgCode, mobile);
//        boolean redisFlag = redisUtils.setEx(mobile, msgCode, 15 * 60 * 60L);
//        log.info("发送短信验证码结果：{}", redisFlag);
//
//        return R.ok();
//    }

    /**
     * 发送短信验证码
     *
     * @return
     */
    @NoLoginAuthRequired
    @RequestMapping(value = "/wxapp/sendRegSmsCode", method = RequestMethod.POST)
    @ResponseBody
    public R sendRegSmsCode(@RequestBody JSONObject json) {
        String mobile = json.getString("mobile");
        if (StringUtils.isEmpty(mobile) || mobile.length() != 11) {
            return R.error("手机号码输入不合法");
        }

        String msgCode = UUIDUtil.generateInteger(4);
        sendMailConfig.sendRegMsg(msgCode, mobile);
        boolean redisFlag = redisUtils.setEx("SMSCODE_" + mobile, msgCode, 15 * 60L);
        //log.info("发送短信验证码结果：{}", redisFlag);

        return R.ok();
    }

    /**
     * 注册商户
     *
     * @param registerInfo
     * @return
     * @throws Exception
     */
    @NoLoginAuthRequired
    @RequestMapping(value = "/wxapp/registerMerchant", method = RequestMethod.POST)
    @ResponseBody
    public R registerMerchant(@RequestBody MerchantRegisterInfo registerInfo) throws Exception {

        if (StringUtils.isEmpty(registerInfo.getMobilePhone())) {
            return R.error("手机号必填");
        }

        if (StringUtils.isEmpty(registerInfo.getSmsCode())) {
            return R.error("手机验证码必填");
        }

        String redisCode = redisUtils.getString("SMSCODE_" + registerInfo.getMobilePhone());
        if (!registerInfo.getMobilePhone().equals("0000") && StringUtils.isEmpty(redisCode)) {
            return R.error("验证码已经失效");
        }

        if (!redisCode.equals(registerInfo.getSmsCode())) {
            return R.error("验证码错误");
        }

        //String openId = (String)request.getSession().getAttribute(Constant.CURR_OPEN_ID);

        if (StringUtils.isBlank(registerInfo.getOpenId())) {
            return R.error("openId为空");
        }

        UserInfoDO user = userInfoService.getByWxOpenId(registerInfo.getOpenId());
        if (user != null) {
            R r = new R();
            r.put("code", 101);
            r.put("msg", "此微信用户已注册");
            return r;
        }

        int ret = merchantService.saveMerchant(registerInfo);
        if (ret > 0) {
            return R.ok("商户注册成功");
        } else {
            return R.error("商户注册失败");
        }
    }


    /**
     * 注册商户
     *
     * @param registerInfo
     * @return
     * @throws Exception
     */
    @NoLoginAuthRequired
    @RequestMapping(value = "/wxapp/updateMerchant", method = RequestMethod.POST)
    @ResponseBody
    public R updateMerchant(@RequestBody MerchantRegisterInfo registerInfo) throws Exception {

        if (StringUtils.isEmpty(registerInfo.getMobilePhone())) {
            return R.error("手机号必填");
        }

        if (registerInfo.getIsPhoneChanged() == 1) {
            if (StringUtils.isEmpty(registerInfo.getSmsCode())) {
                return R.error("手机验证码必填");
            }

            String redisCode = redisUtils.getString("SMSCODE_" + registerInfo.getMobilePhone());
            if (!registerInfo.getMobilePhone().equals("0000") && StringUtils.isEmpty(redisCode)) {
                return R.error("验证码已经失效");
            }

            if (!redisCode.equals(registerInfo.getSmsCode())) {
                return R.error("验证码错误");
            }
        }

        int ret = merchantService.updateMerchant(registerInfo);
        if (ret > 0) {
            return R.ok("商户修改成功");
        } else {
            return R.error("商户修改失败");
        }
    }


    /**
     * 注册商户
     *
     * @param registerInfo
     * @return
     * @throws Exception
     */
    @NoLoginAuthRequired
    @RequestMapping(value = "/wxapp/checkSmsCode", method = RequestMethod.POST)
    @ResponseBody
    public R checkSmsCode(@RequestBody MerchantRegisterInfo registerInfo) throws Exception {

        if (StringUtils.isEmpty(registerInfo.getMobilePhone())) {
            return R.error("手机号必填");
        }

        if (StringUtils.isEmpty(registerInfo.getSmsCode())) {
            return R.error("手机验证码必填");
        }

        String redisCode = redisUtils.getString("SMSCODE_" + registerInfo.getMobilePhone());
        if (!registerInfo.getMobilePhone().equals("0000") && StringUtils.isEmpty(redisCode)) {
            return R.error("验证码已经失效");
        }

        if (!redisCode.equals(registerInfo.getSmsCode())) {
            return R.error("验证码错误");
        }

        return R.ok("验证码检查通过");
    }

    /**
     * 文件上传
     */
    @ResponseBody
    @RequestMapping(value = "/wxapp/uploadImg", method = RequestMethod.POST)
    public R upload(@RequestParam("file") MultipartFile file,
                    @RequestParam("openId") String openId) {
        try {
            String osName = System.getProperty("os.name");
            String licensePath = licenseLinuxPath;
            if (osName.contains("Windows") || osName.contains("windows")) {
                licensePath = licenseWinPath;
            }
            if (licensePath.startsWith("file:")) {
                licensePath = licensePath.substring(5);
            }
            String licPath = licensePath + openId;
            File licenseFolder = new File(licPath);
            if (!licenseFolder.exists()) {
                licenseFolder.mkdir();
            }
            FileUtil.delFolderFiles(licPath);
            //将原有目录下的图片清除掉
            String logoName = FileUtil.getLicenseFileName(file.getOriginalFilename());
            File logoFile = new File(licPath + File.separator + logoName);
            file.transferTo(logoFile);

            String licensePhotoPath = "/license/" + openId + "/" + logoName;

            R r = R.ok();
            r.put("licensePhotoPath", licensePhotoPath);

            return r;


        } catch (Exception e) {
            e.printStackTrace();
            return R.error("上传失败");
        }

    }

    /**
     * 注册普通用户（住户）
     *
     * @param registerInfo
     * @return
     * @throws Exception
     */
    @NoLoginAuthRequired
    @RequestMapping(value = "/wxapp/registerResident", method = RequestMethod.POST)
    @ResponseBody
    public R registerResident(@RequestBody ResidentRegisterInfo registerInfo) throws Exception {

        if (StringUtils.isEmpty(registerInfo.getMobilePhone())) {
            return R.error("手机号必填");
        }

        if (StringUtils.isEmpty(registerInfo.getSmsCode())) {
            return R.error("手机验证码必填");
        }

        String redisCode = redisUtils.getString("SMSCODE_" + registerInfo.getMobilePhone());
        if (!registerInfo.getMobilePhone().equals("0000") && StringUtils.isEmpty(redisCode)) {
            return R.error("验证码已经失效");
        }

        if (!redisCode.equals(registerInfo.getSmsCode())) {
            return R.error("验证码错误");
        }

        //String openId = (String)request.getSession().getAttribute(Constant.CURR_OPEN_ID);

        if (StringUtils.isBlank(registerInfo.getOpenId())) {
            return R.error("openId为空");
        }

        UserInfoDO user = userInfoService.getByWxOpenId(registerInfo.getOpenId());
        if (user != null) {
            R r = new R();
            r.put("code", 101);
            r.put("msg", "此微信用户已注册");
            return r;
        }

        int ret = residentService.saveResident(registerInfo);
        if (ret > 0) {
            return R.ok("普通用户注册成功");
        } else {
            return R.error("普通用户注册失败");
        }
    }


    /**
     * 修改普通用户
     *
     * @param registerInfo
     * @return
     * @throws Exception
     */
    @NoLoginAuthRequired
    @RequestMapping(value = "/wxapp/updateResident", method = RequestMethod.POST)
    @ResponseBody
    public R updateResident(@RequestBody ResidentRegisterInfo registerInfo) throws Exception {

        if (StringUtils.isEmpty(registerInfo.getMobilePhone())) {
            return R.error("手机号必填");
        }

        if (registerInfo.getIsPhoneChanged() == 1) {
            if (StringUtils.isEmpty(registerInfo.getSmsCode())) {
                return R.error("手机验证码必填");
            }

            String redisCode = redisUtils.getString("SMSCODE_" + registerInfo.getMobilePhone());
            if (!registerInfo.getMobilePhone().equals("0000") && StringUtils.isEmpty(redisCode)) {
                return R.error("验证码已经失效");
            }

            if (!redisCode.equals(registerInfo.getSmsCode())) {
                return R.error("验证码错误");
            }
        }

        int ret = residentService.updateResident(registerInfo);
        if (ret > 0) {
            return R.ok("普通用户修改成功");
        } else {
            return R.error("普通用户修改失败");
        }
    }

    /**
     * 保存车辆信息
     *
     * @return
     */
    @RequestMapping(value = "/wxapp/addCar", method = RequestMethod.POST)
    @ResponseBody
    public R addCar(@RequestBody JSONObject json) {

        CarInfoDO carInfoDO = new CarInfoDO();
        carInfoDO.setUserId(json.getLong("userId"));
        carInfoDO.setCarNo(json.getString("carNo"));
        carInfoDO.setCommunityId(json.getLong("communityId"));
        int save = carInfoService.save(carInfoDO);
        if (save <= 0) {
            return R.error();
        }
        return R.ok();
    }

    @ResponseBody
    @RequestMapping(value = "/wxapp/listCars", method = RequestMethod.POST)
    public R listCars(@RequestBody JSONObject json) {

        QueryDO queryDO = new QueryDO();
        queryDO.setPage(1);
        queryDO.setLimit(1000);
        Query query = new Query(queryDO);

        query.put("userId", json.getLong("userId"));
        List<CarInfoDO> cars = carInfoService.list(query);

        R r = R.ok();
        r.put("cars", cars);

        return r;
    }

    @RequestMapping("/wxapp/getCommunitys")
    public R getCommunitys() {
        Query query = new Query();
        query.put("offset", 0);
        query.put("limit", 1000);
        query.put("status", 1);
        query.put("page", 1);

        List<CommunityInfoDO> communityInfos = communityInfoService.list(query);

        R r = R.ok();
        r.put("communitys", communityInfos);

        return r;

    }

    @ResponseBody
    @RequestMapping(value = "/wxapp/getRentPriceByCarNumber", method = RequestMethod.POST)
    public R getRentPriceByCarNumber(@RequestBody JSONObject json) {

        CarPriceRelaDO carPriceRela = carPriceRelaService.getByCarNumber(json.getString("carNumber"));

        R r = R.ok();
        r.put("price", carPriceRela.getAmt().setScale(2, BigDecimal.ROUND_HALF_DOWN));

        return r;
    }

    @ResponseBody
    @RequestMapping(value = "/wxapp/getRentPriceByCarAndCommunity", method = RequestMethod.POST)
    public R getRentPriceByCarAndCommunity(@RequestBody JSONObject json) {

        CarPriceRelaDO carPriceRela = carPriceRelaService.getByCarNumber(json.getString("carNumber"));

        R r = R.ok();
        r.put("price", carPriceRela.getAmt().setScale(2, BigDecimal.ROUND_HALF_DOWN));

        return r;
    }

    @ResponseBody
    @RequestMapping(value = "/wxapp/getRentPriceByCarId", method = RequestMethod.POST)
    public R getRentPriceByCarId(@RequestBody JSONObject json) {

        CarPriceRelaDO carPriceRela = carPriceRelaService.get(json.getLong("carId"));

        R r = R.ok();
        r.put("price", carPriceRela.getAmt().setScale(2, BigDecimal.ROUND_HALF_DOWN));

        return r;
    }

}
